package com.rongc.client.freight.business.carrier.view.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.rongc.client.core.gson.GsonHelper;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.business.carrier.request.api.ConveyanceHasList2MatchApi;
import com.rongc.client.freight.business.carrier.view.fragment.ConveyanceDetailFragment;
import com.rongc.client.freight.business.mine.view.activity.AuthHostActivity;
import com.rongc.client.freight.business.supply.model.CommentBean;
import com.rongc.client.freight.business.supply.model.SupplyBean;
import com.rongc.client.freight.business.supply.request.api.SupplyDetailApi;
import com.rongc.client.freight.business.supply.view.fragment.AddressFragment;
import com.rongc.client.freight.business.supply.view.fragment.SupplyCommentListFragment;
import com.rongc.client.freight.business.supply.view.fragment.UserFragment;
import com.rongc.client.freight.business.waybill.request.api.WaybillTrucksCreateApi;
import com.rongc.client.freight.utils.UtilMethod;
import com.viewpagerindicator.TabPageIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.flyco.dialog.widget.NormalDialog.STYLE_TWO;

/**
 * Created by Bruce on 2017/7/7.
 */
public class ConveyanceSupplyDetailActivity extends BaseActivity implements View.OnClickListener{
    private static final String[] CONTENT = new String[] { "货源详情", "车主评价"};

    @Bind(R.id.pager)
    ViewPager pager;
    @Bind(R.id.indicator)
    TabPageIndicator indicator ;

    FragmentPagerAdapter adapter;
    ConveyanceDetailFragment mYJSFragment;
    SupplyCommentListFragment mWJSFragment;
    List<Fragment> mFragments = new ArrayList<Fragment>();

    UserFragment userFragment;
    AddressFragment addressFragment;

    String conveyanceId;
    SupplyBean supplyBean;
    List<CommentBean> commentBeanList;

    String waybillId;

    NormalDialog dialog;
    NormalDialog authDialog;

    Response.Listener<JSONObject> respDetailListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                try {
                    supplyBean = GsonHelper.getDeserializer().fromJson(response.getString("goodsInfo"), SupplyBean.class);
                    CommentBean[] commenta = GsonHelper.getDeserializer().fromJson(response.getString("replayList"), CommentBean[].class);
                    commentBeanList.clear();
                    if(commenta != null)
                        for (int i=0;i<commenta.length;i++){
                            commentBeanList.add(commenta[i]);
                        }

                    mYJSFragment.setData(supplyBean);

                    userFragment.setData(supplyBean.getImg(),supplyBean.getNick(),
                            supplyBean.getXiadanNumber(),supplyBean.getJiedanNumber(),
                            response.optJSONObject("rateInfo").optString("rate"),supplyBean.getMobile());
                    userFragment.hidePhone();
                    addressFragment.setData(supplyBean);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                UtilMethod.dismissProgressDialog(ConveyanceSupplyDetailActivity.this);
            }
        }
    };

    Response.Listener<JSONObject> respCreateListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                waybillId = response.optString("id");
                //  跳转到司机找货详情
                Bundle bundle = new Bundle();
                bundle.putString("conveyanceId",conveyanceId);
                bundle.putString("waybillId",waybillId);
                ActivityUtils.startActivity(ConveyanceSupplyDetailActivity.this,ConveyanceWaybillDetailActivity.class,bundle);

                finish();
            } else {
                UtilMethod.dismissProgressDialog(ConveyanceSupplyDetailActivity.this);
            }
        }
    };

    Response.Listener<JSONObject> respMatchListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                String status = response.optString("status");
                if("1".equals(status)){
                    //  进入列表
                    Bundle bundle = new Bundle();
                    bundle.putString("supplyId",supplyBean.getId());
                    bundle.putString("price",supplyBean.getFreightByType());
                    bundle.putSerializable("supply",supplyBean);
                    ActivityUtils.startActivity(ConveyanceSupplyDetailActivity.this, ConveyanceList2MatchActivity.class,bundle);
                }else{

                    Bundle bundle = new Bundle();
                    bundle.putString("supplyId",supplyBean.getId());
                    bundle.putString("price",supplyBean.getFreightByType());
                    bundle.putSerializable("supply",supplyBean);
                    ActivityUtils.startActivity(ConveyanceSupplyDetailActivity.this, ConveyanceCreateActivity.class,bundle);
                }
                finish();
            } else {
                UtilMethod.dismissProgressDialog(ConveyanceSupplyDetailActivity.this);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(ConveyanceSupplyDetailActivity.this);
        }
    };

    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                if(UniApplication.getInstance().isAuth()) {
                    String number = supplyBean.getMobile();
                    if(StringUtils.isNotEmpty(waybillId)){
                        ActivityUtils.callTo(this,number);
                    }else
                    ActivityUtils.callTo(this,number,
                            getResources().getString(R.string.conveyance_supply_detail_1), dialog);

                }else{
                    doAuth();
                }
                break;
        }
    }

    @Override
    public void onAuth() {
        if(UniApplication.getInstance().isAuth()) {
            String number = supplyBean.getMobile();
            ActivityUtils.callTo(this,number,
                    getResources().getString(R.string.conveyance_supply_detail_1),dialog);

        }else{
            if(UniApplication.getInstance().isAuthIng())
                ActivityUtils.toast("您已提交申请，还在审核当中");
            else
                authDialog.show();
        }
    }

    @Override
    public void initData() {
        SupplyDetailApi p = new SupplyDetailApi(new SupplyDetailApi.SupplyDetailParams(
                supplyBean.getId()),
                respDetailListener, errorListener);
        RequestManager.getInstance().call(p);
    }

    @Override
    public void initParams() {
        supplyBean = (SupplyBean) getIntent().getSerializableExtra("data");
        conveyanceId = getIntent().getStringExtra("conveyanceId");
        waybillId = getIntent().getStringExtra("waybillId");
    }


    @Override
    public void initView() {
        initToolbar(R.string.conveyance_supply_detail_title);
        commentBeanList = new ArrayList<>();
        userFragment = (UserFragment) getSupportFragmentManager().findFragmentByTag("user");
        addressFragment = (AddressFragment) getSupportFragmentManager().findFragmentByTag("address");

        if(mFragments != null && mFragments.size() == 0){
            mYJSFragment = ConveyanceDetailFragment.getInstance();
            mWJSFragment = SupplyCommentListFragment.getInstance();
            mFragments.add(mYJSFragment);
            mFragments.add(mWJSFragment);
        }

        adapter = new GoogleMusicAdapter(getSupportFragmentManager());

        pager.setAdapter(adapter);
        pager.setOffscreenPageLimit(2);

        indicator.setVisibility(View.VISIBLE);
        indicator.setViewPager(pager);

        makeDialog();
        makeAuthDialog();
    }

    void makeDialog(){
        dialog = new NormalDialog(this);
        dialog.isTitleShow(false)
                .content(getResources().getString(R.string.conveyance_supply_detail_2))
                .style(STYLE_TWO)
                .btnText(new String[]{"没谈好","接单"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        if(StringUtils.isNotEmpty(waybillId)){

                        }else if(StringUtils.isEmpty(conveyanceId)) {
                            // 从找货界面进来，不绑定车源
                            ConveyanceHasList2MatchApi p = new ConveyanceHasList2MatchApi(new ConveyanceHasList2MatchApi.ConveyanceHasList2MatchParams(),
                                    respMatchListener, errorListener);
                            RequestManager.getInstance().call(p);


                        }else{
                            // 绑定车源
                            WaybillTrucksCreateApi p = new WaybillTrucksCreateApi(new WaybillTrucksCreateApi.WaybillTrucksCreateParams(
                                    conveyanceId,supplyBean.getId(),supplyBean.getFreightByType()),
                                    respCreateListener, errorListener);
                            RequestManager.getInstance().call(p);
                        }
                        dialog.cancel();
                    }
                });
    }

    void makeAuthDialog(){
        authDialog = new NormalDialog(this);
        authDialog.title(getResources().getString(R.string.auth_dialog_title))
                .content(getResources().getString(R.string.auth_contact_label))
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","立即认证"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        authDialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        ActivityUtils.startActivity(ConveyanceSupplyDetailActivity.this, AuthHostActivity.class);
                        authDialog.cancel();
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_conveyance_supply_detail;
    }

    class GoogleMusicAdapter extends FragmentPagerAdapter {
        public GoogleMusicAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if(mYJSFragment == null)
                        mYJSFragment = ConveyanceDetailFragment.getInstance();
                    return mYJSFragment;
                case 1:
                    if(mWJSFragment == null) {
                        mWJSFragment = SupplyCommentListFragment.getInstance();
                    }
                    return mWJSFragment;
                default:
                    break;
            }

            return mFragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return CONTENT[position % CONTENT.length].toUpperCase();
        }

        @Override
        public int getCount() {
            return CONTENT.length;
        }
    }
}
